package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCarMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final String DEFAULT = "1";
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    /**
     * 插入订单
     *
     * @param orders
     */
    public void insertOrder(Orders orders) {
        orderMapper.insertOrder(orders);
    }

    /**
     * 更新订单
     *
     * @param orders
     */
    public void updateOrder(Orders orders) {
        orderMapper.updateOrder(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
//    @Transactional
    public void repetitionOrder(Long id) {
        Orders OldOder = orderMapper.getOrderById(id);//复制当前订单数据
        OldOder.setId(null);
        Orders newOrder = insertOrderInfo(OldOder);
        Long OldOderId = id;//旧id
        Long newOrderId = newOrder.getId();//需要插入订单详情表的id 新
        repetitionOrderInfo(newOrderId,OldOderId);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    public void cancelOrder(Long id) {
        Orders orders = Orders.builder().id(id).build();
        orders.setStatus(Orders.CANCELLED);
        orderMapper.updateOrder(orders);
    }


    /**
     * 提交订单
     *
     * @param orders
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(Orders orders) {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder().id(orders.getAddressBookId()).userId(BaseContext.getCurrentId()).build();
        AddressBook address = addressBookMapper.getAddressById(addressBook);
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Orders order = insertOrderInfo(orders);
        //插入订单详情表
        Long orderId = order.getId();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCartList = shoppingCarMapper.getShoppingCartList(shoppingCart);
//        if (shoppingCartList != null && shoppingCartList.size() > 0) {
//            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
//        }
        insertOrderDetail(orderId);

        OrderSubmitVO vo = orderMapper.selectOrderById(orders);
        return vo;
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    public OrderVO detailOrder(Long id) {
        Long userId = BaseContext.getCurrentId();
        OrderVO vo = new OrderVO();
        Orders order = orderMapper.getOrderById(id);
        List<Long> ids = new ArrayList<>();
        if (order != null) {
            ids.add(order.getId());
        }
        BeanUtils.copyProperties(order, vo);


        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(ids);
        vo.setOrderDetailList(orderDetails);
        return vo;
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        Long userId = BaseContext.getCurrentId();

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> result = new ArrayList<>();

        // 提取订单 ID 列表
        List<Long> ids = new ArrayList<>();
        if (orders != null && !orders.isEmpty()) {
            for (Orders order : orders) {
                ids.add(order.getId());
            }
        }

            // 查询订单详情列表
            List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(ids);

            // 创建一个列表来存储 OrderVO 对象
//            List<OrderVO> result = new ArrayList<>();
            if (orders != null && !orders.isEmpty()) {
                for (Orders order : orders) {
                    // 创建 OrderVO 对象
                    OrderVO orderVO = new OrderVO();

                    // 使用 BeanUtils.copyProperties 复制 Orders 对象的属性到 OrderVO 对象
                    BeanUtils.copyProperties(order, orderVO);

                    // 找到当前订单对应的订单详情
                    List<OrderDetail> detailsForOrder = orderDetails.stream()
                            .filter(detail -> detail.getOrderId().equals(order.getId()))
                            .collect(Collectors.toList());

                    // 设置 orderDetailList 字段
                    orderVO.setOrderDetailList(detailsForOrder);

                    // 设置 orderDishes 字段
                    orderVO.setOrderDishes("这里是订单菜品信息");

                    // 添加到结果列表
                    result.add(orderVO);
                }
            }


        long total = orders.getTotal();
        return new PageResult(total, result);

    }

    /**
     * 查询所有订单状态
     * @return
     */
    public OrderStatisticsVO getOrderStatistics() {
        // 查询所有订单
        List<Orders> list = orderMapper.list();

        // 初始化统计对象
        OrderStatisticsVO statistics = new OrderStatisticsVO();
        statistics.setConfirmed(0);
        statistics.setDeliveryInProgress(0);
        statistics.setToBeConfirmed(0);

        // 遍历订单列表，统计不同状态的订单数量
        for (Orders order : list) {
            Integer status = order.getStatus();
            switch (status) {
                case 2: // 待接单
                    statistics.setToBeConfirmed(statistics.getToBeConfirmed() + 1);
                    break;
                case 3: // 已接单（待派送）
                    statistics.setConfirmed(statistics.getConfirmed() + 1);
                    break;
                case 4: // 派送中
                    statistics.setDeliveryInProgress(statistics.getDeliveryInProgress() + 1);
                    break;
                default:
                    // 其他状态不统计
                    break;
            }
        }

        return statistics;
    }

    /**
     * 获取所有订单
     * @return
     */
    public List<OrderVO> getOrderDetailAll(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageResult pageResult = pageQuery(ordersPageQueryDTO);
        // 获取分页结果中的订单列表
        List<OrderVO> orderList =  pageResult.getRecords();
        List<OrderVO> result = new ArrayList<>();


// 遍历订单列表，处理每个订单
        for (OrderVO orderVO : orderList) {
            // 获取订单详情列表
            List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
            // 将订单详情列表中的菜品名称转换为一个字符串
            String orderDishes = orderDetailList.stream()
                    .map(OrderDetail::getName) // 假设 OrderDetail 有一个 getName 方法
                    .collect(Collectors.joining(", ")); // 用逗号和空格分隔

            // 设置 orderDishes 属性
            orderVO.setOrderDishes(orderDishes);

            // 清除 orderDetailList
            orderVO.setOrderDetailList(null);
            result.add(orderVO);
        }
        return result;
    }


    /**
     * 获取用户地址
     *
     * @param addressBook
     * @return
     */
    private String AddressBook(AddressBook addressBook) {
        String province_name = addressBook.getProvinceName();
        String city_name = addressBook.getCityName();
        String detail = addressBook.getDetail();
        String address = province_name + city_name + detail;
        return address;
    }

    /**
     * 订单id
     *
     * @return
     */
    private String orderNumber() {
        LocalDateTime deltime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSnnnnnnnnn");
        String orderNumber = deltime.format(formatter);
        return orderNumber;
    }

    /**
     * 批量插入订单详情表
     * @param orderId
     */
    private void insertOrderDetail(Long orderId) {
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoppingCarMapper.getShoppingCartList(shoppingCart);
        List<OrderDetail> orderDetailList = new ArrayList<>();

            Long id = orderId;
            Orders order = orderMapper.getOrderById(id);
            // 遍历购物车列表，将每个购物车项的数据封装到订单详情对象中
            for (ShoppingCart cart : shoppingCartList) {
                // 创建订单详情对象
                OrderDetail orderDetail = new OrderDetail();
                // 设置订单ID
                orderDetail.setOrderId(order.getId());
                // 设置菜品口味
                orderDetail.setDishFlavor(cart.getDishFlavor());
                // 设置菜品图片
                orderDetail.setImage(cart.getImage());
                // 设置菜品数量
                orderDetail.setNumber(cart.getNumber());
                // 设置菜品名称
                orderDetail.setName(cart.getName());
                // 设置菜品ID（如果购物车中存储了菜品ID）
                orderDetail.setDishId(cart.getDishId());
                // 设置套餐ID（如果购物车中存储了套餐ID）
                orderDetail.setSetmealId(cart.getSetmealId());
                // 设置菜品总价（数量 * 单价）
                orderDetail.setAmount(cart.getAmount());

                // 将订单详情对象添加到列表中
                orderDetailList.add(orderDetail);
            }


        orderDetailMapper.insertBatch(orderDetailList);

    }

    /**
     * 填写订单基础信息
     * @param orders
     * @return
     */
    private Orders insertOrderInfo(Orders orders) {
        //补全信息
        AddressBook addressBook = addressBookMapper.getAddressByIdToOrder(orders.getAddressBookId());
        String address = AddressBook(addressBook);
        String orderNumber = orderNumber();
        orders.setNumber(orderNumber);
        orders.setAddress(address);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.insertOrder(orders);

        return orders;
    }

    /**
     *
     * @param OldOderId 复制订单id
     * @param newOderId 新订单id
     * @return List<ShoppingCart>
     */
    private List<ShoppingCart> repetitionOrderInfo(Long newOderId,Long OldOderId) {
        List<Long> ids = new ArrayList<>();
        ids.add(OldOderId);

        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(ids);
        List<OrderDetail> orderDetailList = new ArrayList<>();


        // 遍历购物车列表，将每个购物车项的数据封装到订单详情对象中
        for (OrderDetail cart : orderDetails) {
            // 创建订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            // 设置订单ID
            orderDetail.setOrderId(newOderId);
            // 设置菜品口味
            orderDetail.setDishFlavor(cart.getDishFlavor());
            // 设置菜品图片
            orderDetail.setImage(cart.getImage());
            // 设置菜品数量
            orderDetail.setNumber(cart.getNumber());
            // 设置菜品名称
            orderDetail.setName(cart.getName());
            // 设置菜品ID（如果购物车中存储了菜品ID）
            orderDetail.setDishId(cart.getDishId());
            // 设置套餐ID（如果购物车中存储了套餐ID）
            orderDetail.setSetmealId(cart.getSetmealId());
            // 设置菜品总价（数量 * 单价）
            orderDetail.setAmount(cart.getAmount());

            // 将订单详情对象添加到列表中
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        return null;
    }
}
